package pe.gob.foncodes.ssa.web.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
import org.apache.log4j.Logger;
import pe.gob.foncodes.ssa.bs.administracion.controller.GenericMaintenanceController;
import pe.gob.foncodes.ssa.bs.common.util.Constante;
import pe.gob.foncodes.ssa.bs.seguridad.domain.Usuario;

public class Impresion extends GenericMaintenanceController{

    static final Logger log = Logger.getLogger(Impresion.class);
    
    public void imprimirListado(String nameReport, Collection coleccion) throws ClassNotFoundException, IOException, JRException{
        imprimirListado(nameReport, coleccion, "");
    }

    public void imprimirListado(String nameReport, Collection coleccion, String filtro)
            throws ClassNotFoundException, IOException, JRException {
        try {
            HashMap parameters = new HashMap();
            FacesContext context = FacesContext.getCurrentInstance();
            context.responseComplete();
            ServletContext scontext = (ServletContext) context.getExternalContext().getContext();
            String rutaReportes = scontext.getRealPath("//reportes");
            String rutaLogos = scontext.getRealPath("//resource//images");
            HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
            response.setContentType("application/pdf");
            response.addHeader("Content-disposition", "attachment; filename=" + nameReport + ".pdf");
            ServletOutputStream out = response.getOutputStream();
            String rutaLeft = rutaLogos + "//" + "logo.png";
            String rutaRight= rutaLogos + "//" + "logo_midis.png";
            String rutaCheck= rutaLogos + "//" + "Check.png";
            String rutaNoCheck= rutaLogos + "//" + "NoCheck.png";
            parameters.put("V_PATH_LEFT", rutaLeft);
            parameters.put("V_PATH_RIGHT", rutaRight);
            parameters.put("V_CHECK",rutaCheck);
            parameters.put("V_NOCHECK",rutaNoCheck);
            if(filtro!= null){
                parameters.put("V_FILTRO", filtro);
            }
            Usuario usuario = (Usuario) getSpringBean(Constante.SESSION_USER);
            parameters.put("V_USER",usuario.getCodUsuario());
            JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(coleccion);
            File reporte = new File(rutaReportes + "//" + nameReport + ".jasper");
            FileInputStream in = new FileInputStream(reporte);
            byte[] bytes = JasperRunManager.runReportToPdf(in, parameters, dataSource);
            out.write(bytes, 0, bytes.length);
            out.flush();
            out.close();
        } catch (Exception ex) {
            log.error(ex);
        } finally {
            FacesContext.getCurrentInstance().responseComplete();
        }
    }
    public void imprimirListado(String nameReport, Collection coleccion, HashMap parameters)
            throws ClassNotFoundException, IOException, JRException {
        try {
            HashMap param = new HashMap();
            param = parameters;
            FacesContext context = FacesContext.getCurrentInstance();
            context.responseComplete();
            ServletContext scontext = (ServletContext) context.getExternalContext().getContext();
            String rutaReportes = scontext.getRealPath("//reportes");
            String rutaLogos = scontext.getRealPath("//resource//images");
            HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
            response.setContentType("application/pdf");
            response.addHeader("Content-disposition", "attachment; filename=" + nameReport + ".pdf");
            ServletOutputStream out = response.getOutputStream();
            String rutaLeft = rutaLogos + "//" + "logo.png";
            String rutaRight= rutaLogos + "//" + "logo_midis.png";
            param.put("V_PATH_LEFT", rutaLeft);
            param.put("V_PATH_RIGHT", rutaRight);
            JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(coleccion);
            File reporte = new File(rutaReportes + "//" + nameReport + ".jasper");
            FileInputStream in = new FileInputStream(reporte);
            byte[] bytes = JasperRunManager.runReportToPdf(in, param, dataSource);
            out.write(bytes, 0, bytes.length);
            out.flush();
            out.close();
        } catch (Exception ex) {
            log.error(ex);
        } finally {
            FacesContext.getCurrentInstance().responseComplete();
        }
    }
    
    public void exportarExcel(String nameReport, Collection coleccion, String filtro)
            throws ClassNotFoundException, IOException, JRException {
        try {
            HashMap parameters = new HashMap();
            FacesContext context = FacesContext.getCurrentInstance();
            context.responseComplete();
            ServletContext scontext = (ServletContext) context.getExternalContext().getContext();
            String rutaReportes = scontext.getRealPath("//reportes");
            String rutaLogos = scontext.getRealPath("//resource//images");
            HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
            response.setContentType("application/vnd.ms-excel");
            response.addHeader("Content-disposition", "attachment; filename=" + nameReport + ".xls");
            ServletOutputStream out = response.getOutputStream();
            String rutaLeft = rutaLogos + "//" + "logo.png";
            String rutaRight= rutaLogos + "//" + "logo_midis.png";
            //String rutaCheck= rutaLogos + "//" + "Check.png";
            //String rutaNoCheck= rutaLogos + "//" + "NoCheck.png";
//            parameters.put("V_PATH_LEFT", rutaLeft);
//            parameters.put("V_PATH_RIGHT", rutaRight);
            //parameters.put("V_CHECK",rutaCheck);
            //parameters.put("V_NOCHECK",rutaNoCheck);
            if(filtro!= null){
                parameters.put("V_FILTRO", filtro);
            }
            Usuario usuario = (Usuario) getSpringBean(Constante.SESSION_USER);
            parameters.put("V_USER",usuario.getCodUsuario());
            JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(coleccion);
            File reporte = new File(rutaReportes + "//" + nameReport + ".jasper");
            FileInputStream in = new FileInputStream(reporte);

            ByteArrayOutputStream output = new ByteArrayOutputStream();
            JasperPrint jasperPrint = JasperFillManager.fillReport(in, parameters, dataSource );
            JRXlsExporter exporterXLS = new JRXlsExporter();
            exporterXLS.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint);
            exporterXLS.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, output);
            exporterXLS.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE);
            exporterXLS.setParameter(JRXlsExporterParameter.IS_DETECT_CELL_TYPE, Boolean.FALSE);
            exporterXLS.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
            exporterXLS.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
            //exporterXLS.setParameter(JRXlsExporterParameter.IGNORE_PAGE_MARGINS, Boolean.TRUE);
            exporterXLS.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_COLUMNS, Boolean.TRUE);
            
            exporterXLS.setParameter(JRXlsExporterParameter.IS_COLLAPSE_ROW_SPAN, Boolean.TRUE);
            //exporterXLS.setParameter(JRXlsExporterParameter.IS_IGNORE_GRAPHICS, Boolean.TRUE);
            
            exporterXLS.exportReport();  
            
            byte[] bytes = output.toByteArray();             
            
            out.write(bytes, 0, bytes.length);
            out.flush();
            out.close();
        } catch (Exception ex) {
            log.error(ex);
        } finally {
            FacesContext.getCurrentInstance().responseComplete();
        }
    }
    
        public void exportarExcel(String nameReport, Collection coleccion, HashMap parameters)
            throws ClassNotFoundException, IOException, JRException {
        try {
            HashMap param = new HashMap();
            param = parameters;
            FacesContext context = FacesContext.getCurrentInstance();
            context.responseComplete();
            ServletContext scontext = (ServletContext) context.getExternalContext().getContext();
            String rutaReportes = scontext.getRealPath("//reportes");
            String rutaLogos = scontext.getRealPath("//resource//images");
            HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
            response.setContentType("application/vnd.ms-excel");
            response.addHeader("Content-disposition", "attachment; filename=" + nameReport + ".xls");
            ServletOutputStream out = response.getOutputStream();
            String rutaLeft = rutaLogos + "//" + "logo.png";
            String rutaRight = rutaLogos + "//" + "logo_midis.png";
            param.put("V_PATH_LEFT", rutaLeft);
            param.put("V_PATH_RIGHT", rutaRight);
            
            JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(coleccion);
            File reporte = new File(rutaReportes + "//" + nameReport + ".jasper");
            FileInputStream in = new FileInputStream(reporte);

            ByteArrayOutputStream output = new ByteArrayOutputStream();
            JasperPrint jasperPrint = JasperFillManager.fillReport(in, param, dataSource );
            JRXlsExporter exporterXLS = new JRXlsExporter();
            exporterXLS.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint);
            exporterXLS.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, output);
            exporterXLS.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.TRUE);
            exporterXLS.setParameter(JRXlsExporterParameter.IS_DETECT_CELL_TYPE, Boolean.TRUE);
            exporterXLS.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
            exporterXLS.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
            exporterXLS.exportReport();  
            
            byte[] bytes = output.toByteArray();
            out.write(bytes, 0, bytes.length);
            out.flush();
            out.close();
        } catch (Exception ex) {
            log.error(ex);
        } finally {
            FacesContext.getCurrentInstance().responseComplete();
        }
        
    }
}
